from PySide2.QtWidgets import (QApplication, QMainWindow, QDateEdit, QListView, 
                                QPushButton, QInputDialog, QMessageBox, QFileDialog)
from PySide2.QtGui import QStandardItemModel, QStandardItem
from PySide2.QtCore import QDate, Qt
import os
from adelegate import myDelegate


class mywindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Date and File")
        self.setGeometry(300, 80, 750, 550)
        # 日期选择器
        self.dateedit = QDateEdit(self)
        self.dateedit.setCalendarPopup(True)
        self.dateedit.setDate(QDate.currentDate())
        self.dateedit.dateChanged.connect(self.showdata)
        self.dateedit.setGeometry(50, 20, 150, 30)
        # 添加新项的按钮
        self.appendbtn = QPushButton("Append data", self)
        self.appendbtn.clicked.connect(self.appenditem)
        self.appendbtn.setGeometry(250, 20, 100, 30)
        # 保存文件的按钮
        self.savebtn = QPushButton("Save to file", self)
        self.savebtn.clicked.connect(self.savefile)
        self.savebtn.setGeometry(400, 20, 100, 30)
        # 列表
        self.listview = QListView(self)
        self.listview.setGeometry(50, 70, 650, 450)
        self.model = QStandardItemModel()
        self.listview.setModel(self.model)
        delegate = myDelegate(self.listview)       # 自定义委托
        self.listview.setItemDelegate(delegate) 
        self.listview.setEditTriggers(QListView.DoubleClicked | QListView.SelectedClicked)
        self.listview.setSelectionMode(QListView.SingleSelection)  # 单选
        self.model.dataChanged.connect(self.dataChanged)  # 数据改变时检查
        # 显示当前日期的数据
        self.showdata()

    def showdata(self):
        '''显示选中日期的数据'''
        self.model.clear()
        date = self.dateedit.date().toString("yyyy-MM-dd")
        # 若没有读取的文件，则创建一个空文件
        if not os.path.exists("data.txt"): 
            open("data.txt", "w").close()  # 创建文件
            return
        # 读取对应日期的数据
        with open(f"data.txt", "r") as file:
            lines = file.readlines()
            if not lines or not any(date in line for line in lines): 
                item = QStandardItem("No data.")
                item.setCheckable(True)
                item.setData("No data.", Qt.UserRole + 1)
                self.model.appendRow(item)
                return
            for line in lines:
                # 处理对应日期的行数据
                if date in line: self.dealdata(line.strip())

    def dealdata(self, line):
        '''处理每一行数据'''
        date, row, check, main, note = line.split(",")
        item = QStandardItem(main)         # 主文本
        item.setCheckable(True)            # 可选中
        item.setCheckState(Qt.Checked if check == "√" else Qt.Unchecked)  # 选中状态
        item.setData(note, Qt.UserRole + 1)  # 备注
        self.model.appendRow(item)

    def appenditem(self):
        '''添加新项'''
        # 弹出输入对话框
        text, ok = QInputDialog.getText(self, "Input", "Enter new item:")
        if ok and text:
            item = QStandardItem(text)         # 主文本
            item.setCheckable(True)            # 可选中
            item.setData("", Qt.UserRole + 1)  # 备注为空
            self.model.appendRow(item)

    def savefile(self):
        '''保存数据到文件'''
        date = self.dateedit.date().toString("yyyy-MM-dd")
        # 弹出文件对话框，选择保存的文件
        filename, _ = QFileDialog.getSaveFileName(self, "Save File", "", "Text Files (*.txt);;All Files (*)")
        if not filename: return
        # 读取数据
        lines = []
        with open(filename, "r") as file:
            lines = file.readlines()
        # 删除当前日期的数据
        lines = [line for line in lines if not line.startswith(date)]
        # 添加当前日期的数据
        for row in range(self.model.rowCount()):
            item = self.model.item(row)
            check = "√" if item.checkState() == Qt.Checked else "x"  # 选中状态
            main = item.text()                    # 主文本
            note = item.data(Qt.UserRole + 1)    # 备注
            lines.append(f"{date},{row},{check},{main},{note}\n")
        # 按日期和行号排序
        lines.sort(key=lambda x: (x.split(",")[0], x.split(",")[1]))
        # 保存到文件
        with open("data.txt", "w") as file:
            file.writelines(lines)
        QMessageBox.information(self, "Info", "Data saved successfully.") 

    def dataChanged(self, index):
        '''数据改变时检查'''
        item = self.model.item(index.row())
        main = item.text()                    # 主文本
        note = item.data(Qt.UserRole + 1)     # 备注
        if not main.strip() and not note.strip():
            self.model.removeRow(index.row())


if __name__ == "__main__":
    app = QApplication()
    window = mywindow()
    window.show()
    app.exec_()